<!--
 * @Author: Wushiqi
 * @Descripttion: 事件委托
 * @Date: 2021-05-07 14:51:14
 * @LastEditor: Wushiqi
 * @LastEditTime: 2021-05-07 16:40:07
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>事件委托</title>
  <ul id="ul1">
    <li>这是li1</li>
    <li>这是li2</li>
    <li>这是li3</li>
    <li>这是li4</li>
    <li>这是li5</li>
  </ul>
  <div id="btns">
    <button id="add">新增</button>
    <button id="update">修改</button>
  </div>
  <div id="boxs">
    <div class="boxnull">null</div>
    <div class="box1">1</div>
    <div class="box2">2</div>
    <div class="box3">3</div>
  </div>
  <style>
    #boxs div[class^=box] {
      display: inline-block;
      margin: 10px;
      width: 100px;
      height: 100px;
      background-color: burlywood;
    }
  </style>
</head>
<body>
  <script>
    window.onload = function() {
      const doc = document // 访问局部比全局变量更快
      // 利用事件的冒泡属性，点击子级事件会传递到父级，因此处理父级的点击事件就行
      const ul1 = doc.getElementById('ul1')
      ul1.onclick = function(ev) {
        const target = ev.target
        if (target.nodeName.toLowerCase() === 'li') {
           console.log('点击的是li标签');
        }
      }

      // 每个点击事件的处理结果可以不一样
      const btns = doc.getElementById('btns')
      btns.onclick = function(ev) {
        const target = ev.target
        switch (target.id) {
          case 'add':
            console.log('新增');
            const boxChild = document.createElement('div')
            boxChild.className = 'box4'
            boxs.appendChild(boxChild)
            break
          case 'update':
            console.log('修改');
            break
          default:
            break
        }
      }

      // 新添加的元素也有事件-点击新增按钮添加砖块
      var boxs = doc.getElementById('boxs')
      boxs.onmousedown = function(ev) {
        const target = ev.target
        if ((/box\d+/).test(target.className)) {
          target.style.background = "#8DC84A"
        }
      }
      boxs.onmouseup = function(ev) {
        const target = ev.target
        if ((/box\d+/).test(target.className)) {
          target.style.background = '#DEB887'
        }
      }
    }
  </script>
</body>
</html>